<?php
namespace App\Tools;

use Smallsha\Classes\Redis;

class Lock
{
    protected $redis;
    protected $lockKey;

    public function __construct($key)
    {
        $this->redis = Redis::getInstance('127.0.0.1');
        $this->lockKey = 'LOCK_PREFIX' . $key;
    }

    /**
     * 自动管理锁
     * @param \Closure $callback
     */
    public function lock(\Closure $callback)
    {
        $is_lock = $this->redis->setnx($this->lockKey, 1); // 加锁
        if ($is_lock == true) { // 获取锁权限
            // 释放锁
            $callback();
            $this->release();
        } else {
            $this->preventDeadlock();
        }
    }

    /**
     * 手动管理锁方式
     * @param \Closure $callback
     * @return mixed
     */
    public function startLock(\Closure $callback)
    {
        $is_lock = $this->redis->setnx($this->lockKey, 1); // 加锁
        var_dump($is_lock);
        if ($is_lock == true) { // 获取锁权限
            return $callback();
        } else {
            $this->preventDeadlock();
        }
    }

    public function release()
    {
        var_dump('release');
        $this->redis->del($this->lockKey);
    }

    private function preventDeadlock()
    {
        var_dump('preventDeadlock');
        // 防止死锁
        if ($this->redis->ttl($this->lockKey) == -1) {
            $this->redis->expire($this->lockKey, 5);
        }
    }
}